from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from app import db

# 管理员-角色关联表（多对多）
AdminRole = db.Table(
    'admin_roles',
    db.Column('admin_id', db.Integer, db.ForeignKey('admins.id'), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id'), primary_key=True)
)

# 角色-权限关联表（多对多）
RolePermission = db.Table(
    'role_permissions',
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id'), primary_key=True),
    db.Column('permission_id', db.Integer, db.ForeignKey('permissions.id'), primary_key=True)
)

class Admin(db.Model):
    """管理员模型"""
    __tablename__ = 'admins'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='用户名')
    name = db.Column(db.String(64), comment='姓名')
    _password_hash = db.Column(db.String(256), nullable=False, comment='密码哈希')
    email = db.Column(db.String(64), unique=True, index=True, comment='邮箱')
    phone = db.Column(db.String(20), unique=True, index=True, comment='手机号')
    is_active = db.Column(db.Boolean, default=True, comment='是否活跃')
    last_login = db.Column(db.DateTime, comment='最后登录时间')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    roles = db.relationship('Role', secondary=AdminRole, backref=db.backref('admins', lazy='dynamic'), lazy='dynamic')
    
    @property
    def password(self):
        """密码属性不可读"""
        raise AttributeError('密码不可读')
    
    @password.setter
    def password(self, password):
        """设置密码，自动进行哈希处理"""
        self._password_hash = generate_password_hash(password)
    
    def verify_password(self, password):
        """验证密码"""
        return check_password_hash(self._password_hash, password)
    
    def has_permission(self, permission):
        """检查是否有指定权限"""
        for role in self.roles:
            for perm in role.permissions:
                if perm.code == permission:
                    return True
        return False
    
    def __repr__(self):
        return f'<Admin {self.id}: {self.username}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'username': self.username,
            'name': self.name,
            'email': self.email,
            'phone': self.phone,
            'is_active': self.is_active,
            'last_login': self.last_login.strftime('%Y-%m-%d %H:%M:%S') if self.last_login else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'roles': [role.name for role in self.roles]
        }


class Role(db.Model):
    """角色模型"""
    __tablename__ = 'roles'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='角色名称')
    description = db.Column(db.String(255), comment='角色描述')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    permissions = db.relationship('Permission', secondary=RolePermission, 
                                backref=db.backref('roles', lazy='dynamic'), lazy='dynamic')
    
    def __repr__(self):
        return f'<Role {self.id}: {self.name}>'
    
    def to_dict(self, with_permissions=False):
        """转换为字典，用于API响应"""
        result = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None
        }
        
        if with_permissions:
            result['permissions'] = [perm.to_dict() for perm in self.permissions]
            
        return result


class Permission(db.Model):
    """权限模型"""
    __tablename__ = 'permissions'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='权限名称')
    code = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='权限代码')
    description = db.Column(db.String(255), comment='权限描述')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def __repr__(self):
        return f'<Permission {self.id}: {self.name}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'name': self.name,
            'code': self.code,
            'description': self.description
        }